<?php

declare(strict_types=1);

namespace app\admin\controller;

use think\facade\Request;
use think\facade\View;
use think\facade\Db;
use app\admin\service\Auth;
use app\common\ConstVar;

class Base
{
    protected $site_config = [];

    /**
     * 构造函数：初始化管理员控制器
     * 检查登录状态、获取站点配置、加载菜单和权限检查
     */
    function __construct()
    {
        // 检查是否已登录
        if (!session('admin_id')) {
            // return redirect('/admin/login');
        }

        $site_config = Db::name('app_config')->select();
        $this->site_config = $site_config;
        View::assign('site_config', $site_config);

        // 获取左侧菜单
        $this->getMenu();
        // 权限检查
        $this->checkAuth();
    }

    /**
     * 获取侧边栏菜单
     * @return void
     */
    protected function getMenu()
    {
        $menu = [];
        $admin_id = 1;
        $auth = new Auth();
        $auth_rule_list = Db::name('auth_rule')->where('status', 1)->order('sort', 'desc')->select();
        foreach ($auth_rule_list as $value) {
            if ($auth->check($value['name'], $admin_id) || $admin_id == 1) {
                $menu[] = $value;
            }
        }

        View::assign('menu', $menu);
    }

    /**
     * 权限检查
     * @return bool
     */
    protected function checkAuth()
    {
        $controller = strtolower(Request::controller());
        $action = strtolower(Request::action());
        $auth_url = $controller . '/' . $action;
        $auth_rule = Db::name('auth_rule')->where('name', $auth_url)->find();

        $group_id = Db::name('auth_group_access')->where('uid', session('uid'))->value('group_id');

        if ($auth_rule) {
            $auth = new Auth();
            $admin_id = session('uid');
            // if (!$auth->check($controller . '/' . $action, $admin_id) && $admin_id !== 1 && $group_id !== 1) {
            //     exit('没有权限');
            // }
        }
    }

    /**
     * 成功提示页跳转，3秒后返回
     * @param string $message 提示信息
     * @param string $url 跳转URL
     * @param int $wait 等待时间(秒)
     * @return mixed
     */
    public function successJump($message, $url, $wait = 3)
    {
        View::assign([
            'message' => $message,
            'url' => $url,
            'wait' => $wait
        ]);
        return View::fetch('common/success');
    }

    /**
     * 错误提示页跳转，3秒后返回
     * @param string $message 提示信息
     * @param string $url 跳转URL
     * @param int $wait 等待时间(秒)
     * @return mixed
     */
    public function errorJump($message, $url, $wait = 3)
    {
        View::assign([
            'message' => $message,
            'url' => $url,
            'wait' => $wait
        ]);
        return View::fetch('common/error');
    }
    /**
     * 生成表格JSON数据
     * @param object $paginationObj 分页对象
     * @param array $items 自定义数据列表（可选）
     * @param int $code 状态码，默认0
     * @param string $msg 消息，默认空
     * @return \think\response\Json JSON响应
     */
    public function genTableJson($paginationObj, $items = [], $code = 0, $msg = '')
    {
        $total = $paginationObj->total();
        if (empty($items)) {
            $items = $paginationObj->items();
        }
        $items = $this->processTableItems($items);

        $res = $this->buildTableJsonResponse($total, $items, $code, $msg);
        return json($res);
    }

    /**
     * 构建表格JSON响应结构
     * @param int $total 总记录数
     * @param array $items 数据列表
     * @param int $code 状态码
     * @param string $msg 消息
     * @return array 响应数组
     */
    private function buildTableJsonResponse($total, $items, $code, $msg)
    {
        return [
            'code' => $code,
            'msg' => $msg,
            'count' => $total,
            'data' => $items
        ];
    }

    /**
     * 处理表格数据项
     * 格式化商品名称、时间等字段
     * @param array $items 原始数据列表
     * @return array 处理后的数据集
     */
    private function processTableItems($items)
    {
        if (count($items)) {
            foreach ($items as $key => $value) {
                if (isset($value['goods']) && $value['goods']) {
                    $items[$key]['goods_name'] = $value['goods']['name'];
                } else {
                    $items[$key]['goods_name'] = '-';
                }
                if (isset($value['goods_id']) && $value['goods_id'] == 41) {
                    $typeName = '';
                    if (isset($value['goods_type']) && $value['goods_type']) {
                        $typeName = ' ' . $value['goods_type']['name'];
                    }
                    if (isset($value['from'])) {
                        $items[$key]['goods_name'] = $value['from'] . '-' . $value['to'] . $typeName;
                    }
                } else {
                    if (isset($value['goods_type']) && $value['goods_type']) {
                        $items[$key]['goods_name'] = $value['goods_type']['name'];
                    }
                }
                if (isset($value['add_time']) && is_numeric($value['add_time'])) {
                    $items[$key]['add_time'] = date('Y-m-d H:i:s', $value['add_time']);
                }
                //规则
                if (isset($value['rule_id'])) {
                    $items[$key]['rule_name'] = isset(ConstVar::$catRules[$value['rule_id']]) ? ConstVar::$catRules[$value['rule_id']]['name'] : '-';
                }
            }
        }
        return $items;
    }
}
